
//Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    int count = 0;
    public int kthSmallest(TreeNode root, int k) {
        if(root.left == null && root.right == null){
            count++;
            return root.val;
        }
        if(root.left != null){
            int left = kthSmallest(root.left, k);
            if(count == k) return left;
        }
        count++;
        if(count == k) return root.val;
        if(root.right != null){
            int right = kthSmallest(root.right, k);
            if(count == k) return right;
        }
        return root.val;
    }
}